package com.dy.security.config;

import com.dy.security.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @Author: ding-yu
 * @Date: 2022/5/19 17:24
 * @Desctiption: (描述)
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserServiceImpl userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //放行注册接口
                .antMatchers("/user/register").permitAll()
                .antMatchers("/user/registerMd5").permitAll()
                .antMatchers("/user/registerNoop").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .csrf()
                .disable();
    }

    /**
     * 放行swagger和knife4j
     * @param web web
     * @throws Exception Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/swagger/**")
                .antMatchers("/swagger-ui.html")
                .antMatchers("/webjars/**")
                .antMatchers("/v2/**")
                .antMatchers("/v3/**")
                .antMatchers("/v2/api-docs-ext/**")
                .antMatchers("/swagger-resources/**")
                .antMatchers("/doc.html");
    }

    /**
     * 配置数据源
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
    /**
     * 密码策略
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        //1.不适使用密码加密
        //return NoOpPasswordEncoder.getInstance();


        //2.使用默认的BCryptPasswordEncoder加密方案
//        return new BCryptPasswordEncoder();


        //3.strength=10 秘钥的迭代次数为10（strength取值在4-31之间，默认为10）
        // return new BCryptPasswordEncoder(10);


        //4.利用工厂类PasswordEncoderFactories实现,工厂类内部采用的是委派密码编码方案.
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

}
